<?php

namespace App\Api\Three\ShopA;

/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use App\Api\ChannelApi;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

//  浙江台州电信接口
class TaiZhouTelecom extends ChannelApi
{
    protected $model;
    protected $salt;
    protected $pname;
    protected $log;
    protected $url;
    protected $appId;
    protected $srcsysid;
    protected $cps;
    protected $cmpid;
    protected $staffPhoneNum;
    protected $salesId; // 产品

    public function __construct($url = '', $str = '')
    {
        // 台州
        $this->pname = 'TaiZhouTelecom';
        $this->log = new Logger('TaiZhouTelecom');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/TaiZhouTelecom.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $params = strToKeyValArr($str);
        $this->url = $url;
        $this->cps = $params['cps']; // cps 代理商标识
        $this->srcsysid = $params['srcsysid']; // srcsysid  接入平台码
        // shopid   cmpid  staffPhoneNum
        $this->appId = $params['shopid']; // 店铺id
        $this->cmpid = $params['cmpid']; // cmpid  
        $this->staffPhoneNum = $params['staffPhoneNum']; // staffPhoneNum  销售人员编码
        $this->salt = $params['key'];  // Key   加密钥匙

    }
    public function sentPost($method, $data)
    {
        // $data = [
        //     'access_token' => $this->accessToken,
        //     'content' => $data,
        //     'method' => ((string)$method),
        //     'version' => (string)"1.0"
        // ];
        // var_dump($data);
        $time = time();
        $headers = [
            'application/json; charset=UTF-8',
        ];

        $url = $this->url . $method;

        // $res = $this->sendBefare($url, $data, $headers);
        $res = $this->sendBefareTwo($url, $data, $headers);
        // var_dump($res, 3333333333);
        if (!empty($res) && is_string($res)) {
            $res = json_decode($res, true);
        }
        return $res;
    }
    public function getToken()
    {
    }
    public function selectNumber($array = [])
    {
    }
    public function checkOrder($array = [])
    {
        // 身份核查
        $method = '/identityCheck';
        $data = [
            'srcsysid' => $this->srcsysid,
            'clientIp' => '127.0.0.1',
            'inputtime' => date('YmdHis'),
            'provinceCode' => '600104',
            'cityCode' => '8331000',
            'custName' => $array['pay_name'],
            'custId' => $array['pay_identity'],
            'salesId' => $array['channel_code']
        ];
        $data['sign'] = $this->getSign($method, $data);
        // var_dump($data);
        $res = $this->sentPost($method, $data);
        // var_dump($res);
        if (!empty($res['status']) && $res['status'] == 200) {
            // 风控
            $resRis = $this->riskChock($array);
            if (!empty($resRis['status']) && $resRis['status'] == 200) {
                return $this->returnMsg(200, '效验成功');
            }
            return $this->returnMsg(106, !empty($resRis['err']) ? $resRis['err'] : '身份效验不过', ['msg' => !empty($resRis['err']) ? $resRis['err'] : '风控效验不过']);
        }
        return $this->returnMsg(106, !empty($res['err']) ? $res['err'] : '身份效验不过', ['msg' => !empty($res['err']) ? $res['err'] : '身份效验不过']);
        return $this->returnMsg(200, '效验成功');
    }
    // 风控
    public function riskChock($array = [])
    {
        $method = '/riskCombinationCheck';
        $data = [
            'srcsysid' => $this->srcsysid,
            'clientip' => '127.0.0.1',
            'inputtime' => date('YmdHis'),
            'name' => $array['pay_name'],
            'idCard' => $array['pay_identity'],
            'phone' => $array['pay_phone'],
            'address' => $array['post_address'],
            'province' => $array['post_province'],
            'city' => $array['post_city'],
            'county' => $array['post_area'],
            'orderArea' => '台州市',
            'goodsId' => $array['channel_code'],
        ];
        $data['sign'] = $this->getSign($method, $data);
        $res = $this->sentPost($method, $data);
        // var_dump($res);
        if (!empty($res['status']) && $res['status'] == 200) {
            return $res;
        }
        return $res;
        return $this->returnMsg(200, '效验成功');
    }
    public  function getStatusCode($status, $arrsy = [])
    {
    }
    // 提交上游
    public function orderSubmit($array = [])
    {
        // // 暂时先不发送 返回成功

        // 组装提交数据
        $method = '/implWaistOrderGetThird';
        $time = date('Y-m-d H:i:s');
        $this->setData($array);
        // if (empty($this->salesId)) {
        //     return $this->returnMsg(101, '请联系管理员添加销售品', ['msg' => '请联系管理员添加销售品']);
        // }
        $address = $this->taiZhouTelecomAdress($array['post_province'], $array['post_city'], $array['post_area']);
        if (empty($address['code']) || $address['code'] != 200) {
            return $address;
        }
        if (empty($number)) {
        }
        $times = date('YmdHis');
        $timesNums = mt_rand(11, 99);
        $timeArggent = date('Y-m-d H:i:s', strtotime($times) - $timesNums);
        $ownAddrss = $address['data'];
        $data = [
            'srcsysid' => $this->srcsysid,
            'clientip' => '127.0.0.1',
            'inputtime' => $times,
            'cps' => $this->cps,
            'cmpid' => $this->cmpid,
            'shopid' => $this->appId,
            'orderNum' => $array['ordersno'],
            'salesId' => $array['channel_code'],
            'name' => $array['pay_name'],
            'idCard' => $array['pay_identity'],
            'phone' => $array['pay_phone'],
            'address' => $array['post_address'],
            'provinceCode' => $ownAddrss['province_code'],
            'cityCode' => $ownAddrss['city_code'],
            'countyCode' => $ownAddrss['area_code'],
            'province' => $ownAddrss['province'],
            'city' => $ownAddrss['city'],
            'county' => $ownAddrss['area'],
            'ascriptionProvince' => '浙江',  // 号码归属地 暂时写死
            'ascriptionProvinceCode' => '600104', // 号码归属地 暂时写死
            'ascriptionCity' => '台州市',
            'ascriptionCityCode' => '8331000',
            'staffPhoneNum' => $this->staffPhoneNum,
            'onAgreementTime' => $timeArggent,
        ];
        $data['sign'] = $this->getSign($method, $data);
        $res = $this->sentPost($method, $data);
        // var_dump($res);
        if (is_string($res)) {
            $res = json_decode($res, true);
        }
        if (isset($res['status']) && $res['status'] == 200) {
            return $this->returnMsg(
                200,
                ((!empty($res['head'])  && !empty($res['head']['msg'])) ? $res['head']['msg'] : '下单成功'),
                [
                    'msg' => ((!empty($res['head'])  && !empty($res['head']['msg'])) ? $res['head']['msg'] : '下单成功'),
                    'order_id' => !empty($res['apiNum']) ? $res['apiNum'] : '',
                ]
            );
        }
        return $this->returnMsg(101, (!empty($res['head']) && !empty($res['head']['err'])) ? $res['head']['err'] : '提交上游失败', ['msg' => (!empty($res['head']) && !empty($res['head']['err'])) ? $res['head']['err'] : '提交上游失败']);

        return $this->returnMsg(100, '提交失败', ['order_id' => !empty($res) ? $res : '']);
    }
    // 不同套餐 设置的参数不一样
    public function setData($data)
    {
        switch ($data['channel_code']) {
            case 'lmk.cps.ybhllxcardwhyxhlwzbhebqqxxkjyxgs29_2022.152888098_Y23010288647':
                $this->salesId = '00000000D892352EDFF97DA7E053AC1410ACD7E6ssp071';
                break;
            case 'lmk.cps.ybhllxcardwhyxhlwzbhebqqxxkjyxgs39_2022.152888098_Y23010288647':
                $this->salesId = '00000000DA7A1BFFB4BB22F6E053AC1410AC30DD';
                break;
        }
        return '';
    }
    // 查询订单 查询
    public function queryOrderStatus($array = [])
    {
        $method = '/api/orderSelect';
        $data = [
            'orderNo' => $array['ordersno'],
            'beginTime' => !empty($array['created_at']) ? date('Y-m-d', strtotime('-1 day', $array['created_at'])) : date('Y-m-d', strtotime('-1 day')),
            'endTime' => date('Y-m-d', strtotime('+1 day')),
        ];
        // var_dump($data);
        $res = $this->sentPost($method, $data);
        return json_decode($res, true);
    }
    // 处理数据 将数据处理成统一格式
    public function queryOneOrder($array = [])
    {
        $res = $this->queryOrderStatus($array);
        if (empty($res['data'])) {
            return $this->returnMsg(100, '数据为空');
        }
        // var_dump($res);
        $getData = $res['data'][0];
        $statusDatas = [
            0 => '提交中',
            1 => '提交上游',
            // 2 => '拒收单',
            10 => '审核中',
            11 => '待发货',
            20 => '已发货',
            30 => '已签收',
            40 => '已激活',
            50 => '异常单',
            51 => '取消单',
            60 => '失败单'
        ];
        $returnStatusArr = array(
            '待发货' => 11,
            '已发货待激活' => 20,
            '已激活' => 40,
            '超时未激活' => 51,
            '激活失败' => 50,
            '激活失败' => 50,
            '实名制失败' => 50
        );
        $data = [
            'id' => $getData['orderno'],
            'sup_order' => $getData['orderno'],
            'created_at' => date('Y-m-d H:i:s', strtotime($getData['stime'])),
            'order_desc' => !empty($getData['deliveryTime']) ? $getData['deliveryTime'] : '',
            'order_desc_at' => !empty($getData['deliveryTime']) ? date('Y-m-d H:i:s', strtotime($getData['deliveryTime'])) : '',
            'order_num' => $getData['orderno'],
            'express_company' => '京东',
            'express_number' => !empty($getData['oddNumber']) ? $getData['oddNumber'] : '',
            'iccid' => !empty($getData['iccid']) ? $getData['iccid'] : '',
            'province' => !empty($getData['province']) ? $getData['province'] : '',
            'city' => !empty($getData['city']) ? $getData['city'] : '',
            'address' => !empty($getData['address']) ? $getData['address'] : '',
            'status' => !empty($returnStatusArr[$getData['states']]) ? $returnStatusArr[$getData['states']] : '',
            'card_status_desc' => !empty($getData['states']) ? $getData['states'] : ''
        ];
        return $this->returnMsg(200, '查询成功', [$data]);
    }
    public function sendBefare($url, $data, $headers)
    {
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        // var_dump($url);
        ksort($data);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            // CURLOPT_URL => 'https://zj.189.cn/zjcard/impl/identityCheck?srcsysid=qqsmFX100&clientIp=127.0.0.1&inputtime=20230615194052&sign=dce55ed7d7123e3b284069a54aa1036e&salesId=lmk.cps.ybhllxcardwhyxhlwzbhebqqxxkjyxgs29_2022.152888098_Y23010288647&custName=%E6%B5%8B%E8%AF%95&custId=350781196403077349&provinceCode=600104&cityCode=8331000',
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
            // CURLOPT_SSL_VERIFYHOST => false,
            // CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER => array(
                'Content-Type:text/html;charset=UTF-8',
                'Transfer-Encoding:chunked',
                'X-Frame-Options:SAMEORIGIN',
                'Content-Encoding:gzip',
                // 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
                'content-type:text/html;charset=UTF-8'
            ),
        ));

        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $res = curl_error($curl);
            $this->log->info('浙江电信参数:' . json_encode($data) . '接口调用失败:' . $res);
            return $res;
        }
        $this->log->info('浙江电信参数:' . json_encode($data) . 'header参数:' . json_encode($headers) . '返回参数:' . $response);
        curl_close($curl);
        return $response;
    }
    public function sendBefareTwo($url, $data, $headers, $isPost = 1)
    {
        // return 1212222222222;
        $curl = curl_init(); // 启动一个CURL会话
        if (!empty($isPost)) {
            // $url = $url . '?' . http_build_query($data);
        }
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if ($isPost == 1) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包 http_build_query
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_USERAGENT, !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');
        if (!empty($headers)) {
            // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        if (curl_error($curl)) {
            //请求失败，返回错误信息
            $res =  curl_error($curl);
            // var_dump($res, 222222222222);
            return $res;
        }
        curl_close($curl); // 关闭CURL会话
        $this->log->info('台州电信参数:' . json_encode($data) . 'user_agent参数:' . (!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36') . '返回参数:' . $result);
        return $result;
    }
    public function sendBefareGet($url, $data, $headers)
    {
        $curl = curl_init(); // 启动一个CURL会话
        $url = $url . '?data=' . urlencode($data);
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        // var_dump($result, 111111111);
        curl_close($curl); // 关闭CURL会话
        return $result;
    }
    public function getSign($method, $params)
    {
        $b = '';
        if ($method == '/implWaistOrderGetThird') {
            $b = $params['srcsysid'] . $params['clientip'] . $params['inputtime'] . $this->salt . $params['staffPhoneNum'] . $params['idCard'] . $params['salesId'];
        }
        if ($method == '/riskCombinationCheck') {
            $b = $params['srcsysid'] . $this->salt . $params['inputtime'] . $params['idCard'];
        }
        if ($method == '/identityCheck') {
            $b = $params['srcsysid'] . $params['clientIp'] . $params['inputtime'] . $this->salt;
        }
        // var_dump($b, 333333333);
        return md5($b);
    }
    public function getAesKey($str)
    {
        $key = 'K_admin_040506_k';
        // $key = bin2hex($key);
        $str = openssl_encrypt($str, 'AES-128-ECB', $key, 1);
        return strtoupper(bin2hex($str));
    }
    // 发货地址
    public function taiZhouTelecomAdress($province, $city, $area)
    {
        if (empty($province) || empty($city) || empty($area)) {
            return $this->returnMsg(100, '未查询到归属地', ['msg' => '归属地传递不能为空']);
        }
        if (mb_strlen($province) > 2) {
            $province = mb_substr($province, 0, mb_strlen($province) - 1);
        }
        if (mb_strlen($city) > 2) {
            $city = mb_substr($city, 0, mb_strlen($city) - 1);
        }
        if (mb_strlen($area) > 2) {
            $area = mb_substr($area, 0, mb_strlen($area) - 1);
        }
        $res = DB::table('zhejiang_taizhou_telecom')->where('province', 'like', '%' . $province . '%')->where('city', 'like', '%' . $city . '%')->where('area', 'like', '%' . $area . '%')->first();
        if (!$res) {
            return $this->returnMsg(100, '未查询到归属地', ['msg' => '未查询到归属地']);
        }
        return $this->returnMsg(200, '查询成功', ['province' => $res->province, 'city' => $res->city, 'city_code' => $res->city_code, 'province_code' => $res->province_code, 'area_code' => $res->area_code, 'area' => $res->area]);
    }
}
